package com.stupidzhe.vbreview.controller.stu;

import com.stupidzhe.vbreview.bean.ResultBean;
import com.stupidzhe.vbreview.bean.ZipResultBean;
import com.stupidzhe.vbreview.domain.Project;
import com.stupidzhe.vbreview.domain.Student;
import com.stupidzhe.vbreview.domain.UploadProject;
import com.stupidzhe.vbreview.service.ProjectService;
import com.stupidzhe.vbreview.service.StudentService;
import com.stupidzhe.vbreview.service.UploadProjectService;
import com.stupidzhe.vbreview.util.FileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/stu/project")
public class StudentProjectController {

    private final ProjectService projectService;

    private final UploadProjectService uploadProjectService;

    private final StudentService studentService;

    public StudentProjectController(ProjectService projectService, UploadProjectService uploadProjectService, StudentService studentService) {
        this.projectService = projectService;
        this.uploadProjectService = uploadProjectService;
        this.studentService = studentService;
    }

    @RequestMapping({"/", ""})
    public String mainView(@RequestParam(defaultValue = "1", required = false) Integer pageNum,
                           @RequestParam(required = false) String keyword, Model model, HttpServletRequest request) {
        Student student = (Student) request.getAttribute("student");
        model.addAttribute("student", student);
        model.addAttribute("keyword", keyword);
        model.addAttribute("pageBean", projectService.getProjectPageStudentCanSee(pageNum, student.getClassId(), keyword));
        return "stu/stu.project";
    }

    /**
     * 详情页
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String detail(@PathVariable("id") Integer projectId, Model model, HttpServletRequest request) {
        Student student = (Student) request.getAttribute("student");
        Project project = projectService.getProjectWithTimesById(projectId, student.getUserId());
        List<UploadProject> list = uploadProjectService.getList(projectId, student.getUserId());
        model.addAttribute("project", project);
        model.addAttribute("list", list);
        return "stu/stu.project.detail";
    }

    @ResponseBody
    @RequestMapping(value = "/{id}", method = RequestMethod.POST)
    public ResultBean addStudentProject(@PathVariable("id") Integer projectId, @RequestParam("projectLocation") String projectLocation,
                                        HttpServletRequest request) {
        Student student = (Student) request.getAttribute("student");
        return uploadProjectService.addUploadProject(student.getUserId(), projectId, projectLocation);
    }

    @RequestMapping(value = "/uploadProject/{projectId}", method = RequestMethod.POST)
    @ResponseBody
    public ResultBean uploadProject(@RequestParam(value = "projectFile") MultipartFile file,
                                    HttpServletRequest request, @PathVariable("projectId") Integer projectId) {
        String fileName = file.getOriginalFilename();
        String[] nameArr = fileName.split("[.]");

        // 判断上传作业格式
        if (!nameArr[nameArr.length - 1].equals("rar")
                && !nameArr[nameArr.length - 1].equals("zip")) {
            return new ResultBean(false, "文件格式出错");
        }

        // 判断是否作弊
        Student student = (Student) request.getAttribute("student");
        if (!student.getStudentNum().equals(nameArr[0].split("[-]")[0])) {
            return new ResultBean(false, "登录学生与提交作业学号不同");
        }

        // 判断是否通过
        boolean res = uploadProjectService.isPass(projectId, student.getUserId());
        if (res) {
            return new ResultBean(false, "已通过，无需再上传");
        }

        // 判断是否已达上限res = uploadProjectService.isMax(projectId, student.getUserId());
        if (res) {
            return new ResultBean(false, "作业上传已达到最大限度");
        }


        // 判断作业名称格式
        try {
            res = studentService.validate(nameArr[0].split("[-]")[0]);
            if (!res) {
                return new ResultBean(false, "学号不存在");
            }
        } catch (Exception e) {
            return new ResultBean(false, "上传格式错误.\n(提示:文件夹名称为\"学号-作业名称\",压缩文件与原文件夹名称相同）");
        }

        String name = null;
        ZipResultBean zipResultBean = null;
        try {
            zipResultBean = FileUtil.unzip(file.getBytes(), nameArr[0], nameArr[nameArr.length - 1]);
            if (!zipResultBean.isSuccess()) {
                return new ResultBean(false, zipResultBean.getMsg());
            }
            return new ResultBean(true, zipResultBean.getName());

        } catch (IOException e) {
            e.printStackTrace();
            return new ResultBean(false, "上传失败");

        }
    }

}
